<?php
/**
 * @author hungnq
 */
class Core_ImageUtil
{
	const DEFAULT_IMAGE_SIZE = 800;
	const IMAGEJPG_QUALITY = 100;
	const DEFAULT_IMAGE_THUMBNAIL_SIZE = 175;
	const DEFAULT_BANNER_THUMBNAIL_SIZE = 100;
	/**
	 *
	 * @param type $imageType
	 * @return array functions 
	 */
	public static function initFunction($fileName)
	{
		$arrFunction = array();
		$imageType	= exif_imagetype($fileName);
		switch($imageType)
		{
			case IMAGETYPE_JPEG:
				$arrFunction[] = 'imagecreatefromjpeg';
				$arrFunction[] = 'imagejpeg';
				break;
			case IMAGETYPE_PNG:
				$arrFunction[] = 'imagecreatefrompng';
				$arrFunction[] = 'imagepng';
				break;
			case IMAGETYPE_GIF:
				$arrFunction[] = 'imagecreatefromgif';
				$arrFunction[] = 'imagegif';
				break;
			default:
				throw new Exception("Invalid file extension");
				break;
		}
		
		return $arrFunction;
	}
	

	public static function resize($fileName, $newWidth, $newHeight)
	{
		$inputFunction			= '';
		$outputFunction			= '';
		list($width, $height)	= getimagesize($fileName);
		
		$imageType	= exif_imagetype($fileName);
		$source		= null;
		$thumb		= imagecreatetruecolor($newWidth, $newHeight);
	
		list($inputFunction, $outputFunction) = self::initFunction($fileName);
		
		$source = $inputFunction($fileName);
		imagecopyresized($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
		if($imageType == IMAGETYPE_JPEG)
		{
			$outputFunction($thumb, $fileName, self::IMAGEJPG_QUALITY);
		}
		else
		{
			$outputFunction($thumb, $fileName);
		}
		imagedestroy($thumb);
	}
	
	public static function crop($fileName, $newWidth, $newHeight, $srcX = 0, $srcY = 0, $cropHeight = 0, $cropWidth = 0)
	{
		$inputFunction			= '';
		$outputFunction			= '';
		list($width, $height)	= getimagesize($fileName);
		
		$imageType	= exif_imagetype($fileName);
		$source		= null;
		$thumb		= imagecreatetruecolor($newWidth, $newHeight);
	
		list($inputFunction, $outputFunction) = self::initFunction($fileName);
		
		$source = $inputFunction($fileName);
		imagecopyresized($thumb, $source, 0, 0, $srcX, $srcY, $newWidth, $newHeight, $cropWidth, $cropHeight);
		if($imageType == IMAGETYPE_JPEG)
		{
			$outputFunction($thumb, $fileName, self::IMAGEJPG_QUALITY);
		}
		else
		{
			$outputFunction($thumb, $fileName);
		}
		imagedestroy($thumb);
	}
}
